document.addEventListener('DOMContentLoaded', () => {
    const canvas = document.getElementById('gameCanvas');
    const ctx = canvas.getContext('2d');
    const scoreElement = document.getElementById('score');
    const levelElement = document.getElementById('level');
    const lengthElement = document.getElementById('length');
    const highScoreElement = document.getElementById('highScore');
    const startBtn = document.getElementById('startBtn');
    const pauseBtn = document.getElementById('pauseBtn');
    const helpBtn = document.getElementById('helpBtn');
    const gameOverlay = document.getElementById('gameOverlay');
    const overlayTitle = document.getElementById('overlayTitle');
    const overlayMessage = document.getElementById('overlayMessage');
    const helpModal = document.getElementById('helpModal');
    const closeHelp = document.getElementById('closeHelp');
    const modeSelect = document.getElementById('modeSelect');
    const timerBox = document.getElementById('timerBox');
    const timeLeftEl = document.getElementById('timeLeft');
    

    // 游戏设置
    const gridSize = 20;
    const tileCount = canvas.width / gridSize;
    let snake = [{ x: 10, y: 10 }];
    let food = { x: 15, y: 15, type: 'normal' };
    let dx = 1; // x方向速度
    let dy = 0; // y方向速度
    let score = 0;
    let level = 1;
    let highScore = localStorage.getItem('snakeHighScore') || 0;
    let gameLoop;
    let isGameRunning = false;
    let isPaused = false;
    let animationFrame = 0;
    let lastMoveTime = 0;
    let baseSpeed = 150; // 基础速度（毫秒）
    let currentSpeed = baseSpeed;
    let mode = 'classic';
    let timeLeft = 60; // 计时模式剩余时间
    let timerInterval = null;
    let obstacles = [];
    

    // 食物类型定义
    const foodTypes = {
        normal: { color: '#ff6b6b', points: 10, growth: 1, probability: 0.6 },
        gold: { color: '#ffd700', points: 50, growth: 2, probability: 0.25 },
        special: { color: '#4ecdc4', points: 100, growth: 3, probability: 0.12 },
        rainbow: { color: 'rainbow', points: 200, growth: 5, probability: 0.03 }
    };

    // 初始化UI
    highScoreElement.textContent = highScore;
    updateStats();

    // 更新统计信息
    function updateStats() {
        scoreElement.textContent = score;
        levelElement.textContent = level;
        lengthElement.textContent = snake.length;
        highScoreElement.textContent = highScore;
    }

    // 绘制游戏元素
    function draw() {
        // 清空画布
        ctx.fillStyle = '#1a1a1a';
        ctx.fillRect(0, 0, canvas.width, canvas.height);

        // 绘制网格（可选）
        drawGrid();

        // 单机渲染
        drawSnake();
        drawFood();
        drawObstacles();

        // 更新统计信息
        updateStats();
    }

    

    // 绘制网格
    function drawGrid() {
        ctx.strokeStyle = 'rgba(255, 255, 255, 0.1)';
        ctx.lineWidth = 1;
        for (let i = 0; i <= tileCount; i++) {
            ctx.beginPath();
            ctx.moveTo(i * gridSize, 0);
            ctx.lineTo(i * gridSize, canvas.height);
            ctx.stroke();
            
            ctx.beginPath();
            ctx.moveTo(0, i * gridSize);
            ctx.lineTo(canvas.width, i * gridSize);
            ctx.stroke();
        }
    }

    // 绘制蛇
    function drawSnake() {
        snake.forEach((segment, index) => {
            const x = segment.x * gridSize;
            const y = segment.y * gridSize;
            
            if (index === 0) {
                // 蛇头
                const gradient = ctx.createLinearGradient(x, y, x + gridSize, y + gridSize);
                gradient.addColorStop(0, '#4CAF50');
                gradient.addColorStop(1, '#2E7D32');
                ctx.fillStyle = gradient;
                
                // 绘制圆角矩形
                drawRoundedRect(x + 1, y + 1, gridSize - 2, gridSize - 2, 5);
                
                // 绘制眼睛
                ctx.fillStyle = 'white';
                ctx.fillRect(x + 5, y + 5, 3, 3);
                ctx.fillRect(x + 12, y + 5, 3, 3);
            } else {
                // 蛇身
                const gradient = ctx.createLinearGradient(x, y, x + gridSize, y + gridSize);
                gradient.addColorStop(0, '#66BB6A');
                gradient.addColorStop(1, '#4CAF50');
                ctx.fillStyle = gradient;
                
                drawRoundedRect(x + 1, y + 1, gridSize - 2, gridSize - 2, 3);
            }
        });
    }

        // 绘制食物
    function drawFood() {
        const x = food.x * gridSize;
        const y = food.y * gridSize;
        const foodType = foodTypes[food.type];
        
        // 食物闪烁效果
        const pulse = Math.sin(animationFrame * 0.2) * 0.3 + 0.7;
        const size = (gridSize - 2) * pulse;
        const offset = (gridSize - size) / 2;
        
        if (foodType.color === 'rainbow') {
            // 彩虹食物
            const gradient = ctx.createRadialGradient(
                x + gridSize/2, y + gridSize/2, 0,
                x + gridSize/2, y + gridSize/2, size/2
            );
            gradient.addColorStop(0, '#ff6b6b');
            gradient.addColorStop(0.25, '#4ecdc4');
            gradient.addColorStop(0.5, '#45b7d1');
            gradient.addColorStop(0.75, '#96ceb4');
            gradient.addColorStop(1, '#feca57');
            ctx.fillStyle = gradient;
        } else {
            // 普通食物
            const gradient = ctx.createRadialGradient(
                x + gridSize/2, y + gridSize/2, 0,
                x + gridSize/2, y + gridSize/2, size/2
            );
            gradient.addColorStop(0, foodType.color);
            gradient.addColorStop(1, darkenColor(foodType.color, 0.3));
            ctx.fillStyle = gradient;
        }
        
        ctx.beginPath();
        ctx.arc(x + gridSize/2, y + gridSize/2, size/2, 0, Math.PI * 2);
        ctx.fill();
        
        // 添加光晕效果
        ctx.shadowColor = foodType.color;
        ctx.shadowBlur = 10;
        ctx.beginPath();
        ctx.arc(x + gridSize/2, y + gridSize/2, size/2, 0, Math.PI * 2);
        ctx.fill();
        ctx.shadowBlur = 0;
    }

    // 绘制障碍（障碍模式）
    function drawObstacles() {
        if (mode !== 'obstacles') return;
        ctx.fillStyle = '#9e9e9e';
        obstacles.forEach(obs => {
            const x = obs.x * gridSize;
            const y = obs.y * gridSize;
            drawRoundedRect(x + 1, y + 1, gridSize - 2, gridSize - 2, 4);
        });
    }

    // 绘制圆角矩形
    function drawRoundedRect(x, y, width, height, radius) {
        ctx.beginPath();
        ctx.moveTo(x + radius, y);
        ctx.lineTo(x + width - radius, y);
        ctx.quadraticCurveTo(x + width, y, x + width, y + radius);
        ctx.lineTo(x + width, y + height - radius);
        ctx.quadraticCurveTo(x + width, y + height, x + width - radius, y + height);
        ctx.lineTo(x + radius, y + height);
        ctx.quadraticCurveTo(x, y + height, x, y + height - radius);
        ctx.lineTo(x, y + radius);
        ctx.quadraticCurveTo(x, y, x + radius, y);
        ctx.closePath();
        ctx.fill();
    }

    // 颜色变暗函数
    function darkenColor(color, factor) {
        const hex = color.replace('#', '');
        const r = parseInt(hex.substr(0, 2), 16);
        const g = parseInt(hex.substr(2, 2), 16);
        const b = parseInt(hex.substr(4, 2), 16);
        
        return `rgb(${Math.floor(r * (1 - factor))}, ${Math.floor(g * (1 - factor))}, ${Math.floor(b * (1 - factor))})`;
    }

    // 更新游戏状态
    function update() {
        if (!isGameRunning || isPaused) return;

        const currentTime = Date.now();
        if (currentTime - lastMoveTime < currentSpeed) {
            return;
        }

        lastMoveTime = currentTime;

        // 移动蛇：计算下一步位置
        let nextX = snake[0].x + dx;
        let nextY = snake[0].y + dy;

        // 穿墙模式：超出边界则从另一侧出现
        if (mode === 'wrap') {
            if (nextX < 0) nextX = tileCount - 1;
            if (nextX >= tileCount) nextX = 0;
            if (nextY < 0) nextY = tileCount - 1;
            if (nextY >= tileCount) nextY = 0;
        }

        const head = { x: nextX, y: nextY };
        snake.unshift(head);

        // 检测是否吃到食物
        if (head.x === food.x && head.y === food.y) {
            const foodType = foodTypes[food.type];
            const basePoints = foodType.points;
            const levelBonus = Math.floor(basePoints * (level - 1) * 0.1);
            const totalPoints = basePoints + levelBonus;
            
            score += totalPoints;
            
            // 根据食物类型增长蛇的长度
            for (let i = 0; i < foodType.growth - 1; i++) {
                snake.push({ ...snake[snake.length - 1] });
            }
            
            // 检查是否升级
            checkLevelUp();
            
            generateFood();
            showScoreEffect(totalPoints, head.x * gridSize + gridSize/2, head.y * gridSize + gridSize/2);
        } else {
            snake.pop();
        }

        // 检测碰撞
        if (checkCollision()) {
            gameOver();
            return;
        }

        animationFrame++;
        draw();
    }

    // 检查升级
    function checkLevelUp() {
        const newLevel = Math.floor(score / 100) + 1;
        if (newLevel > level) {
            level = newLevel;
            currentSpeed = Math.max(50, baseSpeed - (level - 1) * 10);
            showLevelUpEffect();
        }
    }

    // 显示得分效果
    function showScoreEffect(points, x, y) {
        const effect = document.createElement('div');
        effect.textContent = `+${points}`;
        effect.style.cssText = `
            position: absolute;
            left: ${x}px;
            top: ${y}px;
            color: #4CAF50;
            font-weight: bold;
            font-size: 18px;
            pointer-events: none;
            z-index: 1000;
            animation: scoreEffect 1s ease-out forwards;
        `;
        
        document.body.appendChild(effect);
        
        setTimeout(() => {
            document.body.removeChild(effect);
        }, 1000);
    }

    // 显示升级效果
    function showLevelUpEffect() {
        const effect = document.createElement('div');
        effect.textContent = `等级提升！等级 ${level}`;
        effect.style.cssText = `
            position: fixed;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            color: #ffd700;
            font-weight: bold;
            font-size: 24px;
            pointer-events: none;
            z-index: 1000;
            text-shadow: 2px 2px 4px rgba(0,0,0,0.5);
            animation: levelUpEffect 2s ease-out forwards;
        `;
        
        document.body.appendChild(effect);
        
        setTimeout(() => {
            document.body.removeChild(effect);
        }, 2000);
    }

    // 生成食物
    function generateFood() {
        let newFood;
        do {
            newFood = {
            x: Math.floor(Math.random() * tileCount),
                y: Math.floor(Math.random() * tileCount),
                type: getRandomFoodType()
            };
        } while (
            snake.some(segment => segment.x === newFood.x && segment.y === newFood.y) ||
            (mode === 'obstacles' && obstacles.some(o => o.x === newFood.x && o.y === newFood.y))
        );
        
        food = newFood;
    }

    // 获取随机食物类型
    function getRandomFoodType() {
        const random = Math.random();
        let cumulative = 0;
        
        for (const [type, config] of Object.entries(foodTypes)) {
            cumulative += config.probability;
            if (random <= cumulative) {
                return type;
            }
        }
        
        return 'normal';
    }

    // 检测碰撞
    function checkCollision() {
        const head = snake[0];

        // 墙壁碰撞（非穿墙模式）
        if (mode !== 'wrap') {
        if (head.x < 0 || head.x >= tileCount || head.y < 0 || head.y >= tileCount) {
            return true;
            }
        }

        // 自身碰撞
        for (let i = 1; i < snake.length; i++) {
            if (head.x === snake[i].x && head.y === snake[i].y) {
                return true;
            }
        }

        // 障碍物碰撞
        if (mode === 'obstacles') {
            for (const obs of obstacles) {
                if (head.x === obs.x && head.y === obs.y) return true;
            }
        }

        return false;
    }

    // 游戏结束
    function gameOver() {
        isGameRunning = false;
        isPaused = false;
        
        // 更新最高分
        if (score > highScore) {
            highScore = score;
            localStorage.setItem('snakeHighScore', highScore);
        }
        
        // 显示游戏结束界面
        overlayTitle.textContent = '游戏结束';
        overlayMessage.textContent = `最终分数: ${score} | 最高分: ${highScore}`;
        startBtn.textContent = '重新开始';
        startBtn.style.display = 'inline-block';
        pauseBtn.style.display = 'none';
        gameOverlay.style.display = 'flex';
        
        updateStats();
    }

    // 暂停游戏
    function pauseGame() {
        if (!isGameRunning) return;
        
        isPaused = !isPaused;
        
        if (isPaused) {
            pauseBtn.textContent = '继续';
            overlayTitle.textContent = '游戏暂停';
            overlayMessage.textContent = '按空格键或点击继续按钮恢复游戏';
            gameOverlay.style.display = 'flex';
        } else {
            pauseBtn.textContent = '暂停';
            gameOverlay.style.display = 'none';
        }
    }

    // 控制方向（仅在游戏开始后响应按键）
    function changeDirection(event) {
        const LEFT_KEY = 37;
        const RIGHT_KEY = 39;
        const UP_KEY = 38;
        const DOWN_KEY = 40;
        const SPACE_KEY = 32;
        const W_KEY = 87;
        const A_KEY = 65;
        const S_KEY = 83;
        const D_KEY = 68;

        const keyPressed = event.keyCode;

        if (!isGameRunning || isPaused) return;

        const goingUp = dy === -1;
        const goingDown = dy === 1;
        const goingRight = dx === 1;
        const goingLeft = dx === -1;

        if (keyPressed === SPACE_KEY) {
            event.preventDefault();
            pauseGame();
            return;
        }

        if ((keyPressed === LEFT_KEY || keyPressed === A_KEY) && !goingRight) { dx = -1; dy = 0; }
        if ((keyPressed === UP_KEY || keyPressed === W_KEY) && !goingDown) { dx = 0; dy = -1; }
        if ((keyPressed === RIGHT_KEY || keyPressed === D_KEY) && !goingLeft) { dx = 1; dy = 0; }
        if ((keyPressed === DOWN_KEY || keyPressed === S_KEY) && !goingUp) { dx = 0; dy = 1; }
    }

    // 开始游戏
    function startGame() {
        if (isGameRunning && !isPaused) return;

        // 重置游戏状态
        snake = [{ x: 10, y: 10 }];
        dx = 1;
        dy = 0;
        score = 0;
        level = 1;
        currentSpeed = baseSpeed;
        isGameRunning = true;
        isPaused = false;
        
        // 更新UI
        startBtn.textContent = '游戏中...';
        startBtn.style.display = 'none';
        pauseBtn.style.display = 'inline-block';
        pauseBtn.textContent = '暂停';
        gameOverlay.style.display = 'none';
        
        generateFood();
        if (mode === 'obstacles') generateObstacles();
        if (mode === 'timed') startTimer();
        lastMoveTime = Date.now();
        
        // 使用requestAnimationFrame代替setInterval
        function gameLoop() {
            update();
            if (isGameRunning) {
                requestAnimationFrame(gameLoop);
            }
        }
        gameLoop();
    }

    // 生成障碍（障碍模式）
    function generateObstacles() {
        obstacles = [];
        const count = Math.floor(tileCount * 0.8);
        while (obstacles.length < count) {
            const obs = {
                x: Math.floor(Math.random() * tileCount),
                y: Math.floor(Math.random() * tileCount)
            };
            const conflicts = snake.some(s => s.x === obs.x && s.y === obs.y) ||
                (food && food.x === obs.x && food.y === obs.y) ||
                obstacles.some(o => o.x === obs.x && o.y === obs.y);
            if (!conflicts) obstacles.push(obs);
        }
    }

    // 模式选择
    if (modeSelect) {
        modeSelect.addEventListener('change', () => {
            mode = modeSelect.value;
            if (timerBox) timerBox.style.display = mode === 'timed' ? 'block' : 'none';
            
        });
    }

    // 计时器（计时模式）
    function startTimer() {
        clearInterval(timerInterval);
        timeLeft = 60;
        if (timeLeftEl) timeLeftEl.textContent = timeLeft;
        timerInterval = setInterval(() => {
            if (!isGameRunning || isPaused) return;
            timeLeft--;
            if (timeLeftEl) timeLeftEl.textContent = timeLeft;
            if (timeLeft <= 0) {
                clearInterval(timerInterval);
                overlayTitle.textContent = '时间到！';
                gameOver();
            }
        }, 1000);
    }

    

    

    // 显示帮助
    function showHelp() {
        helpModal.style.display = 'block';
    }

    // 隐藏帮助
    function hideHelp() {
        helpModal.style.display = 'none';
    }

    // 事件监听
    document.addEventListener('keydown', changeDirection);
    startBtn.addEventListener('click', startGame);
    pauseBtn.addEventListener('click', pauseGame);
    helpBtn.addEventListener('click', showHelp);
    closeHelp.addEventListener('click', hideHelp);

    // 点击模态框外部关闭
    window.addEventListener('click', (event) => {
        if (event.target === helpModal) {
            hideHelp();
        }
    });

    // 添加CSS动画
    const style = document.createElement('style');
    style.textContent = `
        @keyframes scoreEffect {
            0% {
                opacity: 1;
                transform: translateY(0) scale(1);
            }
            100% {
                opacity: 0;
                transform: translateY(-50px) scale(1.5);
            }
        }
        
        @keyframes levelUpEffect {
            0% {
                opacity: 1;
                transform: translate(-50%, -50%) scale(1);
            }
            50% {
                transform: translate(-50%, -50%) scale(1.2);
            }
            100% {
                opacity: 0;
                transform: translate(-50%, -50%) scale(1.5);
            }
        }
    `;
    document.head.appendChild(style);

    // 初始绘制
    draw();
});